/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import entity.Alokasi;
import entity.Karyawan;
import entity.Pekerjaan;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;

/**
 *
 * @author Darkman
 */
public class AlokasiDAOImpl extends GeneralDAOImpl implements AlokasiDAO {

    public AlokasiDAOImpl(EntityManager em) {
        super(em);
    }

    public Alokasi get(Long id) throws Exception {
        Alokasi a = null;
        try {
            em.getTransaction().begin();
            a = em.find(Alokasi.class, id);
            em.getTransaction().commit();
        } catch (Exception e) {
            throw e;
        }

        return a;
    }

    public List<Alokasi> gets() throws Exception {
        List<Alokasi> list = new ArrayList<Alokasi>();

        try {
            em.getTransaction().begin();
            list = em.createQuery("SELECT a FROM Alokasi a").getResultList();
            em.getTransaction().commit();
        } catch (Exception e) {
            throw e;
        }

        return list;
    }

    public List<Alokasi> getsByPekerjaan(Pekerjaan p) throws Exception {
        List<Alokasi> list = new ArrayList<Alokasi>();

        try {
            em.getTransaction().begin();
            list = em.createQuery("SELECT a FROM Alokasi a WHERE a.pekerjaan = :p").setParameter("p", p).getResultList();
            em.getTransaction().commit();
        } catch (Exception e) {
            throw e;
        }

        return list;
    }

    public List<Karyawan> getsAvalibleKaryawan(Pekerjaan p) throws Exception {
        List<Karyawan> list = new ArrayList<Karyawan>();
        String query;

        try {
            query = "SELECT k FROM Karyawan k "
                    + "WHERE k.noidentitas NOT IN "
                    + "(SELECT a.karyawan.noidentitas FROM Alokasi a WHERE a.pekerjaan.tglMulai BETWEEN :a AND :b "
                    + "OR "
                    + "a.pekerjaan.tglSelesai BETWEEN :a AND :b)";

            em.getTransaction().begin();
            list = em.createQuery(query).setParameter("a", p.getTglMulai()).setParameter("b", p.getTglSelesai()).getResultList();
            em.getTransaction().commit();
        } catch (Exception e) {
            throw e;
        }

        return list;
    }

    public List<Alokasi> getsByKaryawan(Karyawan k) throws Exception {
        List<Alokasi> list = new ArrayList<Alokasi>();

        try {
            em.getTransaction().begin();
            list = em.createQuery("SELECT a FROM Alokasi a WHERE a.karyawan = :k").setParameter("k", k).getResultList();
            em.getTransaction().commit();
        } catch (Exception e) {
            throw e;
        }

        return list;
    }
}
